package ac.neec.mio.ui.adapter;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.ParcelUuid;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import ac.neec.mio.R;

import java.util.Iterator;
import java.util.List;

import ac.neec.core.ble.util.BleUuid;

/**
 * Created by kobayashi on 2014/01/26.
 */
public class BLEDeviceAdapter extends ArrayAdapter<BluetoothDevice> {
    private LayoutInflater layoutInflater;
    private List<BluetoothDevice> deviceList;

    public BLEDeviceAdapter( Context context, int textViewResourceId, List<BluetoothDevice> deviceList ) {
        super( context, textViewResourceId, deviceList );
        layoutInflater = (LayoutInflater) context
                .getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        this.deviceList = deviceList;
    }

    @Override
    public View getView( int position, View convertView, ViewGroup parent ) {
        BluetoothDevice item = (BluetoothDevice) getItem( position );

        if ( convertView == null ) {
            convertView = layoutInflater.inflate( R.layout.adapter_ble_device, null );
        }

        TextView name = (TextView) convertView.findViewById( R.id.adapter_ble_device_device_name );
        name.setText( item.getName() );

        TextView addr = (TextView) convertView.findViewById( R.id.adapter_ble_device_device_addr );
        addr.setText( item.getAddress() );

        ImageView state = (ImageView) convertView.findViewById( R.id.adapter_ble_device_device_img );


        return convertView;
    }

    @Override
    public synchronized void add( BluetoothDevice device ) {
        String addr = device.getAddress();

        Iterator<BluetoothDevice> it = deviceList.iterator();
        for (; it.hasNext(); ) {
            if ( it.next().getAddress().equals( addr ) ) {
                it.remove();
                break;
            }
        }
        deviceList.add( device );
        notifyDataSetChanged();
    }

    private boolean checkUUIDSupported( BluetoothDevice device ) {
        ParcelUuid[] uuids = device.getUuids();
        for ( ParcelUuid item : uuids ) {
            if ( item.getUuid().toString().equals( BleUuid.SERVICE_HEART_RATE ) ) ;
            return true;
        }
        return false;
    }

    public List<BluetoothDevice> getDeviceList() {
        return deviceList;
    }

    public void deviceClear() {
        deviceList.clear();
        notifyDataSetChanged();
    }

}
